import { fileURLToPath, URL } from 'node:url'

import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
import webExtension from 'vite-plugin-web-extension'

// https://vite.dev/config/
export default defineConfig(({ mode }) => {
  // 加载根目录的环境变量
  const rootEnv = loadEnv(mode, resolve(__dirname, '..'), '')
  // 加载当前目录的环境变量
  const localEnv = loadEnv(mode, __dirname, '')
  const env = { ...rootEnv, ...localEnv }
  return {
    // envDir: resolve(__dirname, '..'),
    define: {
      ...Object.keys(env).reduce(
        (prev, key) => {
          if (key.startsWith('VITE_')) {
            prev[`import.meta.env.${key}`] = JSON.stringify(env[key])
          }
          return prev
        },
        {} as Record<string, string>,
      ),
    },
    plugins: [
      vue(),
      // vueDevTools(),
      webExtension({
        manifest: resolve(__dirname, 'manifest.json'),
        disableAutoLaunch: true,
        additionalInputs: ['src/popup/index.html'],
        skipManifestValidation: true,
      }),
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
      },
    },
  }
})
